import 'package:flutter/material.dart';
import '../../manger/checkspu_utils.dart';
import '../../l10n/app_localizations.dart';
import '../view/confirm_dyinput_view.dart';
import '../../components/toast_utils.dart';
import '../view/confirm_infopop_view.dart';
import '../view/confirm_infopops_view.dart';
class ConfrimInfoViewDelegate {
  VoidCallback? clickShowList;
  VoidCallback? clickSureNext;
  void Function(List<String>)? clickShowTTypeCode;
  void Function(String, String)? onTextChanged;

  ConfrimInfoViewDelegate({
    this.clickShowList,
    this.clickSureNext,
    this.clickShowTTypeCode,
    this.onTextChanged,
  });
}

class ConfrimInfoView extends StatefulWidget {
  final ConfrimInfoViewDelegate? delegate;
  final List<TxInfoModel>? txInfoModels;
  final bool isShowMemberIcon;
  final String areacode;
  final VoidCallback? onTap;
  final String accountId;
  final String rechargeDetail;
  final String rechargeDetailUrl;
  final bool isDy;

  ConfrimInfoView({
    Key? key,
    this.delegate,
    this.txInfoModels,
    required this.isShowMemberIcon,
    required this.accountId,
    required this.areacode,
    required this.rechargeDetail,
    required this.rechargeDetailUrl,
    required this.isDy,
    this.onTap,
  }) : super(key: key);

  @override
  ConfrimInfoViewState createState() => ConfrimInfoViewState();
}

class ConfrimInfoViewState extends State<ConfrimInfoView> {
  late TextEditingController inputTextController;
  late TextEditingController inputText2Controller;
  late TextEditingController inputText3Controller;
  late TextEditingController inputPwdTextController;
  late TextEditingController inputPwdText2Controller;
  late TextEditingController inputTextwController;
  List<String> optionsArray = [];
  final GlobalKey<DyInputViewState> dyInputViewKey = GlobalKey<DyInputViewState>();

  @override
  void initState() {
    super.initState();
    inputTextController = TextEditingController();
    inputText2Controller = TextEditingController();
    inputText3Controller = TextEditingController();
    inputPwdTextController = TextEditingController();
    inputPwdText2Controller = TextEditingController();
    inputTextwController = TextEditingController();

    inputTextController.addListener(() => _notifyTextChange('inputText', inputTextController.text));
    inputText2Controller.addListener(() => _notifyTextChange('inputText2', inputText2Controller.text));
    inputText3Controller.addListener(() => _notifyTextChange('inputText3', inputText3Controller.text));
    inputPwdTextController.addListener(() => _notifyTextChange('inputPwdText', inputPwdTextController.text));
    inputPwdText2Controller.addListener(() => _notifyTextChange('inputPwdText2', inputPwdText2Controller.text));
    inputTextwController.addListener(() => _notifyTextChange('inputTextw', inputTextwController.text));
  }

  @override
  void didUpdateWidget(ConfrimInfoView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.accountId.isNotEmpty) {
      bool hasType0Field = widget.txInfoModels?.any((model) => model.type == 0) ?? false;
      if (hasType0Field) {
        inputTextController.text = widget.accountId;
      } 
    }

  }

  void dyClickListId(String accountId){
    if (mounted) {
        final state = dyInputViewKey.currentState;
        if (state != null) {
          state.dyId = accountId;
          state.clickConfirm();
        }
      }
  }

 List<Map<String, dynamic>> onGetAllValues() {
  List<Map<String, dynamic>> orderParams = [];

  if (widget.txInfoModels == null) return orderParams;

  // 先检查所有必填字段是否为空
  for (var model in widget.txInfoModels!) {
    switch (model.type) {
      case 0:
        if (inputTextController.text.isEmpty && model.required == 1) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }
        break;
      case 1:
        if (widget.areacode.isEmpty && model.required == 1) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }
        break;
      case 2:
        if (inputPwdTextController.text.isEmpty && model.required == 1) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }
        break;
      case 4:
        String dyId = dyInputViewKey.currentState?.dyId ?? "";
        if (dyId.isEmpty) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }

        if (dyInputViewKey.currentState?.sureId == false){
          ToastUtils.showCenterToast(context, "请先确认抖音id");
          return [];
        }
        break;
      case 5:
        if (inputText2Controller.text.isEmpty && model.required == 1) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }
        break;
      case 6:
        if (inputText3Controller.text.isEmpty && model.required == 1) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }
        break;
      case 7:
        if (inputPwdText2Controller.text.isEmpty && model.required == 1) {
          ToastUtils.showCenterToast(context, "${model.name}不能为空");
          return [];
        }
        break;
    }
  }

  // 所有必填字段验证通过后，再收集数据
  for (var model in widget.txInfoModels!) {
    Map<String, dynamic> param = {
      "type": model.type,
      "name": model.name,
      "nameZH": model.nameZH,
      "value": "",
    };

    switch (model.type) {
      case 0:
        param["value"] = inputTextController.text;
        break;
      case 1:
        param["value"] = widget.areacode;
        break;
      case 2:
        param["value"] = inputPwdTextController.text;
        break;
      case 3:
        param["value"] = inputTextwController.text;
        break;
      case 4:
        param["value"] = dyInputViewKey.currentState?.dyId ?? "";
        break;
      case 5:
        param["value"] = inputText2Controller.text;
        break;
      case 6:
        param["value"] = inputText3Controller.text;
        break;
      case 7:
        param["value"] = inputPwdText2Controller.text;
        break;
      default:
        param["value"] = "";
    }

    orderParams.add(param);
  }

  return orderParams;
}


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        margin: const EdgeInsets.only(top: 15, left: 15, right: 15),
        decoration: BoxDecoration(
          color: Color(0xFFEAEAFF),
          borderRadius: BorderRadius.circular(15),
        ),
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _buildNumberLabel('1'),
                SizedBox(width: 8),
                _buildTitleLabel(AppLocalizations.of(context)!.fillInRechargeInformation),
                Expanded(child: Container()),
                GestureDetector(
                  onTap: () {
                    if (!widget.isDy){
                      if (widget.rechargeDetail == ""){
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return CustomOverlayView(
                              onClose: () {
                                Navigator.of(context).pop();
                              },
                            );
                          },
                        );
                      } else {
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return CustomOverlayImageView(
                              imageUrl: widget.rechargeDetailUrl,
                              onClose: () {
                                Navigator.of(context).pop();
                              },
                            );
                          },
                        );
                      }
                    }
                  },
                  child: isChineseLocale() 
                      ? Text(
                          widget.isDy ? "" : widget.rechargeDetail == ""  ? AppLocalizations.of(context)!.howToFillInRechargeInformation : widget.rechargeDetail,
                          style: TextStyle(
                            fontFamily: 'sans-serif',
                            color: widget.isDy ? Color(0xFF5D5FEE) : Color(0xFF666666),
                            fontSize: 13,
                            decoration: widget.isDy ? TextDecoration.none : TextDecoration.underline,
                          ),
                        )
                      : Image.asset('assets/images/howinfo.png', width: 20, height: 20),
         
        
                  ),
                
                SizedBox(width: 10)
              ],
            ),
            _buildMainView(),
          ],
        ),
      ),
    );
  }

  void _notifyTextChange(String fieldName, String value) {
    if (widget.delegate?.onTextChanged != null) {
      widget.delegate!.onTextChanged!(fieldName, value);
    }
  }

  Widget _buildMainView() {
    if (widget.txInfoModels == null || widget.txInfoModels!.isEmpty) {
      return Container();
    }

    return Container(
      decoration: BoxDecoration(
        color: Color(0xFFFFFFFF),
        borderRadius: BorderRadius.circular(15),
      ),
      padding: EdgeInsets.only(left: 15, right: 15, top: 15, bottom: 5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ..._buildDynamicFields(),
        ],
      ),
    );
  }

  List<Widget> _buildDynamicFields() {
    List<Widget> widgets = [];
    for (var model in widget.txInfoModels!) {
      switch (model.type) {
        case 0:
          widgets.addAll([
            _buildRequiredLabel(model.name),
            SizedBox(height: 5),
            _buildInputFieldWithIcon(model.blurb, inputTextController),
            SizedBox(height: 15),
          ]);
          break;
        case 1:
          widgets.addAll([
            _buildRequiredLabel(model.name),
            SizedBox(height: 5),
            _buildDropdownField(model.blurb,model.options),
            SizedBox(height: 15),
          ]);
          break;
        case 2:
          widgets.addAll([
            _buildRequiredLabel(model.name),
            SizedBox(height: 5),
            _buildPasswordField(model.blurb, inputPwdTextController),
            SizedBox(height: 15),
          ]);
          break;
        case 3:
          widgets.addAll([
            _buildTitleLabel(model.name),
            SizedBox(height: 5),
            _buildLargeInputField(model.blurb, inputTextwController),
            SizedBox(height: 15),
          ]);
          break;
        case 4:
          widgets.addAll([
            DyInputView(
              key: dyInputViewKey,
              onClickCheckNext: onClickCheckNext,
              onDyClickShowList: onDyClickShowList,
              blurb: model.blurb,
              isShowMemberIcon: widget.isShowMemberIcon,
              title: model.name,
            ),
            SizedBox(height: 10),
          ]);
          break;
        case 5:
          widgets.addAll([
            _buildRequiredLabel(model.name),
            SizedBox(height: 5),
            _buildInputField2(model.blurb, inputText2Controller),
            SizedBox(height: 15),
          ]);
          break;
        case 6:
          widgets.addAll([
            _buildRequiredLabel(model.name),
            SizedBox(height: 5),
            _buildInputField3(model.blurb, inputText3Controller),
            SizedBox(height: 15),
          ]);
          break;
        case 7:
          widgets.addAll([
            _buildRequiredLabel(model.name),
            SizedBox(height: 5),
            _buildPasswordField2('Password', inputPwdText2Controller),
            SizedBox(height: 15),
          ]);
          break;
      }
    }

    return widgets;
  }

  Widget _buildNumberLabel(String number) => Container(
        width: 18,
        height: 18,
        margin: const EdgeInsets.only(left: 10, top: 10, bottom: 10),
        decoration: BoxDecoration(
          color: Color(0xFF5D5FEE),
          shape: BoxShape.circle,
        ),
        child: Center(
          child: Text(
            number,
            style: TextStyle(color: Colors.white, fontSize: 13),
          ),
        ),
      );

  Widget _buildTitleLabel(String title) => Padding(
        padding: const EdgeInsets.only(top: 0),
        child: Text(
          title,
          style: TextStyle(fontSize: 15, color: Colors.black),
        ),
      );

  Widget _buildDropdown(String title, String options) {
    optionsArray = options.split(',');
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: GestureDetector(
        onTap: _onDropdownTapped,
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
          decoration: BoxDecoration(
            border: Border.all(color: Color(0xFFE6E6E6)),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Flexible(
                child: Text(
                  widget.areacode == '' ? title : widget.areacode,
                  overflow: TextOverflow.ellipsis,
                  softWrap: false,
                  maxLines: 1,
                ),
              ),
              const Icon(Icons.arrow_drop_down),
            ],
          ),
        ),
      ),
    );
  }


  Widget _buildDropdownField(String title,String options) => _buildDropdown(title,options);

  Widget _buildRequiredLabel(String text) => Row(
        children: [
          Container(
            width: 15,
            height: 15,
            alignment: Alignment.center,
            child: Text('*', style: TextStyle(color: Colors.red, fontSize: 15)),
          ),
          SizedBox(width: 3),
          Text(text, style: TextStyle(fontSize: 14, color: Colors.black)),
        ],
      );

  Widget _buildInputFieldWithIcon(String hint, TextEditingController controller) => Container(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
        decoration: BoxDecoration(
          border: Border.all(color: Color(0xFFE6E6E6)),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: controller,
                decoration: InputDecoration.collapsed(
                  hintText: hint,
                  hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
                ),
              ),
            ),
            widget.isShowMemberIcon
                ? GestureDetector(
                    onTap: () {
                      widget.onTap?.call();
                    },
                    child: Image.asset('assets/images/order_icon5.png', width: 20, height: 20),
                  )
                : const SizedBox(),
          ],
        ),
      );

  Widget _buildLargeInputField(String hint, TextEditingController controller) => Container(
      height: 70,
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        border: Border.all(color: Color(0xFFE6E6E6)),
        borderRadius: BorderRadius.circular(8),
      ),
      child: TextField(
        controller: controller,
        maxLines: 3,
        textInputAction: TextInputAction.done,
        onSubmitted: (_) => FocusManager.instance.primaryFocus?.unfocus(),
        decoration: InputDecoration.collapsed(
          hintText: hint,
          hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
        ),
      ),
    );

  Widget _buildInputField2(String hint, TextEditingController controller) => _buildInputField3(hint, controller);

  Widget _buildInputField3(String hint, TextEditingController controller) => Container(
        height: 38,
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
        decoration: BoxDecoration(
          border: Border.all(color: Color(0xFFE6E6E6)),
          borderRadius: BorderRadius.circular(8),
        ),
        child: TextField(
          controller: controller,
          decoration: InputDecoration.collapsed(
            hintText: hint,
            hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ),
      );

  Widget _buildPasswordField(String label, TextEditingController controller) => _buildPasswordField2(label, controller);

  Widget _buildPasswordField2(String label, TextEditingController controller) => Container(
        height: 38,
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
        decoration: BoxDecoration(
          border: Border.all(color: Color(0xFFE6E6E6)),
          borderRadius: BorderRadius.circular(5),
        ),
        child: TextField(
          controller: controller,
          obscureText: true,
          decoration: InputDecoration.collapsed(
            hintText: label,
            hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ),
      );

  void _onDropdownTapped() {
    widget.delegate?.clickShowTTypeCode?.call(optionsArray);
  }

  void onClickCheckNext() {
    widget.delegate?.clickSureNext?.call();
  }

  void onDyClickShowList() {
    widget.delegate?.clickShowList?.call();
  }
}
